// var Util = require('../../utils/util.js')

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// component/KPickerView/KPickerView.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 预约时间 HH:MM
    rTime: {
      type: String,
      observer: function(newValue, oldValue) {
        // 把字符串时间拆分成列表赋值给selectIndexList
        var array = newValue.split(":")
        var hours = this.data.hourList
        var mins = this.data.minList
        var hour = array[0]
        var min = array[1]
        var hourIndex = hours.indexOf(hour)
        var minIndex = mins.indexOf(min)
        this.setData({
          selectIndexList: [hourIndex, minIndex],
        })
      }
    },

    timeViewStatus: {
      type: Number,
      observer: function(newValue, oldVlue){
        var value = newValue > 0
        this.setData({
          showTimeView: value
        })
      }
    },

    canReservation: {
      type: Number,
      observer: function (newValue, oldVlue) {
        var value = newValue > 0
        this.setData({
          reservation: value
        })
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    // 默认支持24小时
    hourList: [
      '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', 
      '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', 
      '20', '21', '22', '23'],
    // 分钟固定为60分钟
    minList: [
      '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', 
      '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', 
      '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', 
      '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', 
      '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', 
      '50', '51', '52', '53', '54', '55', '56', '57', '58', '59'],
    // 选择下标列表
    selectIndexList:[0, 0],
    // 默认完成时间
    finishTime: { 'hour': '0', 'min': '30' },

    showTimeView: false,

    reservation: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 更新选择的时间
    updateTime: function(e){
      var array = e.detail.value
      // 把小时和分钟组成字符串 HH:MM
      var hour = array[0]
      var min = array[1]
      var time = [hour, min].map(formatNumber).join(':')

      var fTime = Util.timeDifference(time)
      this.setData({
        finishTime: { 'hour': fTime.hour, 'min': fTime.min }        
      })

      var eventDetail = { 'time': time, 'enable': true}
      var eventOtional = {}
      this.triggerEvent('value-change-event', eventDetail, eventOtional)
    },

    updateSwitch: function(e){
      var value = e.detail.value
      this.setData({
        showTimeView: value
      })

      var enable = true
      if(!value){
        enable = false
      }
      var eventDetail = { 'enable': enable }
      var eventOtional = {}
      this.triggerEvent('value-change-event', eventDetail, eventOtional)
    },
  },
})
